package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public ValidateCodeVo generateValidateCode() {
        //使用hutool包中的工具类生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        //获取验证码
        String code = circleCaptcha.getCode();
        //获取使用base64加密之后的图片地址
        String imageBase64 = circleCaptcha.getImageBase64();
        //使用UUID随机生成字符串作为验证码的key
        String codeKey = UUID.randomUUID().toString().replaceAll("-", "");
        // 将验证码保存得到Redis中并设置有效时间五分钟
        redisTemplate.opsForValue().set("user:code:"+codeKey,code,5, TimeUnit.MINUTES);
       //创建验证码返回对象
        ValidateCodeVo validateCodeVo=new ValidateCodeVo();
        //设置验证码的key
        validateCodeVo.setCodeKey(codeKey);
        //设置验证码图片地址
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);


        return validateCodeVo;
    }
}
